package com.example.googlemapdrawroutelast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.Provider;
import java.text.RuleBasedCollator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Debug;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.util.TimingLogger;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.api.client.testing.json.AbstractJsonFactoryTest.E;

/**
 * @author Iwona
 * 
 */
public class MainActivity extends FragmentActivity implements LocationListener,
		OnClickListener {
	private ApplicationData appData;
	private RouteData routeData;
	private GoogleMap googleMap;
	private RouteInfo routeInfo;
	private boolean isRouteDrawing;

	// Mapa Data
	private SupportMapFragment fm;
	//

	// Lists
	// coordinate arraylist
	ArrayList<LatLng> markerPoints;
	// Start Stop point
	ArrayList<LatLng> firstLocation;
	ArrayList<String> routeCoordinatesList;
	List<CharacteristicPoint> listOfPoint = new ArrayList<CharacteristicPoint>();
	// markers list
	List<Marker> markersList;
	//
	List<CharacteristicPoint> characteristicPoints;
	//
	List<LatLng> listaWspolrzednych = new ArrayList<LatLng>();
	//
	double mLatitude = 0;
	double mLongitude = 0;
	int mMode = 0;
	// EditText
	EditText etPointDes;
	EditText etPointName;
	EditText etRouteDes;
	EditText etRouteName;
	//
	TextView tvDistanceDuration;
	TextView tvGpsLocation;
	Button buttonAddRoute, buttonAddPoint;
	PopupWindow popupMessage;
	TextView popupText;
	PopupWindow pwindo, pwindopoint;
	Button btnClosePopup, btnShareYourRoute;
	Button btnShareYourPoint, btnClosePopupPoint;

	//
	final Context context = this;
	TextView tvStatus;
	//
	public static String descriptionPoint;
	public static String namePoint;

	//
	Location mLocationClient;
	//
	private Boolean isPressedStartButton = false;
	private Boolean isPressedStopButton = true;
	private MyLocationListener locationListener;
	LatLng startCoordinate;
	Boolean getMenuItem = false;
	// marker - alertdialog
	private Marker marker;
	//
	long time1 = 0;
	long time2 = 0;
	long timeEnd = 0;
			

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_);

		this.appData = new ApplicationData();
		// ///// 		Intent sender = getIntent();

		// Bundle extras = sender.getExtras();
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			int idUser = extras.getInt("idUser");
			if (idUser != 0) {
				this.appData.setIdUser(idUser);
			}

			routeInfo = (RouteInfo) extras.get("route");
			isRouteDrawing = (Boolean) extras.get("isRouteDrawing");
		}

		this.initialise();
		createGoogleMap(savedInstanceState);

		// Starting locations retrieve task
		// new RetrieveTask().execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		// getMenuInflater().inflate(R.menu.main, menu);
		// bool bDisplayMenu =
		// isItemEnabled(((AdapterView.AdapterContextMenuInfo)
		// menuInfo).position);

		if (getMenuItem) {
			getMenuInflater().inflate(R.menu.menu_start_stop, menu);

		}
		return getMenuItem;
	}

	private void showMsg(String msg) {
		Toast toast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
		toast.show();
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		// boolean menusEnabled = reachedEndOfSlidehow();
		switch (item.getItemId()) {

		case R.id.menuStart:

			isPressedStartButton = true;
			isPressedStopButton = false;

			MarkerOptions options = new MarkerOptions();
			options.position(markerPoints.get(SizeOfmarkersPointsArray() - 1));
			options.icon(BitmapDescriptorFactory
					.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
			googleMap.addMarker(options);

			showMsg("Start");
			/*
			 * wpiszWspolrzedne(); onLocationChanged(listaWspolrzednych);
			 */
			// isPressedStartButton = true;
			// return isPressedStartButton;
			return true;

		case R.id.menuStop:

			isPressedStopButton = true;
			isPressedStartButton = false;

			showMsg("Stop");

			MarkerOptions options2 = new MarkerOptions();
			options2.position(markerPoints.get(SizeOfmarkersPointsArray() - 1));
			options2.icon(BitmapDescriptorFactory
					.defaultMarker(BitmapDescriptorFactory.HUE_RED));
			googleMap.addMarker(options2);

			return true;

		case R.id.addPoint:
			//if(isPressedStartButton &&!isPressedStopButton ){
			initiatePopupWindowPoint();
			//}
			//else{
			//	Toast.makeText(getBaseContext(), "Cannot add point. Press Start!",
			//			Toast.LENGTH_SHORT).show();
			//}
			return true;

		case R.id.addRoute:

			initiatePopupWindowRoute();

			return true;

		default:
			return super.onOptionsItemSelected(item);
		}

	}

	public int SizeOfmarkersPointsArray() {
		return markerPoints.size();
	}

	public void AlertDialogDescPoint(String description, String name) {

		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
		builder.setTitle(name);
		builder.setMessage(description);

		/*
		 * builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
		 * { public void onClick(DialogInterface dialog, int id) { // Do
		 * something //getApplicationContext() Intent intent = new
		 * Intent(getApplicationContext(), MainActivity.class);
		 * intent.putExtra("route", routeInfo);
		 * intent.putExtra("isRouteDrawing", false);
		 * //intent.putExtra("route",routeInfo); startActivityForResult(intent,
		 * 0);
		 * 
		 * } });
		 */
		builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				// User cancelled the dialog
			}
		});
		builder.show();
	}

	private void initialise() {

		/*
		 * buttonAddRoute = (Button) findViewById(R.id.sendRoute);
		 * buttonAddRoute.setOnClickListener(this);
		 */

		// text view initial
		tvDistanceDuration = (TextView) findViewById(R.id.tv_distance_time);
		tvStatus = (TextView) findViewById(R.id.tvStatus);
		tvGpsLocation = (TextView) findViewById(R.id.tvGpsLocation);
		// button
		/*
		 * buttonAddPoint = (Button) findViewById(R.id.sendPoint);
		 * buttonAddPoint.setOnClickListener(this);
		 */

	}

	public void initiatePopupWindowRoute() {

		try {
			// We need to get the instance of the LayoutInflater

			LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
					.getSystemService(LAYOUT_INFLATER_SERVICE);

			// View layout = layoutInflater.inflate(R.layout.screen_popup,
			// (ViewGroup) findViewById(R.id.popup_element));

			View layout = layoutInflater.inflate(R.layout.screen_popup,
					(ViewGroup) findViewById(R.id.popup_element));
			pwindo = new PopupWindow(layout, LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT, true);

			// pwindo = new PopupWindow(layout, 250, 350, true);
			pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);

			etRouteDes = (EditText) layout.findViewById(R.id.etDescRoad);
			etRouteName = (EditText) layout.findViewById(R.id.etNameRoad);

			btnShareYourRoute = (Button) layout.findViewById(R.id.send_Route);
			btnShareYourRoute.setOnClickListener(this);

			btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
			btnClosePopup.setOnClickListener(this);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void initiatePopupWindowPoint() {

		try {
			// We need to get the instance of the LayoutInflater

			LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
					.getSystemService(LAYOUT_INFLATER_SERVICE);
			View layout = layoutInflater.inflate(R.layout.screen_popuppoint,
					(ViewGroup) findViewById(R.id.popuppoint_element));

			LayoutInflater li = LayoutInflater.from(context);
			View promptsView = li.inflate(R.layout.screen_popuppoint, null);

			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
					context);

			// set prompts.xml to alertdialog builder
			alertDialogBuilder.setView(promptsView);
			// 250 300
			pwindopoint = new PopupWindow(layout, 250, 350, true);
			pwindopoint.showAtLocation(layout, Gravity.CENTER, 0, 0);

			// etPointName = (EditText)
			// promptsView.findViewById(R.id.etNamePoint);

			etPointName = (EditText) layout.findViewById(R.id.etNamePoint);
			// etPointName.setOnClickListener(this);

			etPointDes = (EditText) layout.findViewById(R.id.etDescPoint);
			// etPointDes.setOnClickListener(this);

			// to ma wartosc nullw watch tzn , nie moge pobrac dancyh z editText
			// czyli tego formularza dlatego ze nie moze sie odwolac do
			// editText etpointnam ei etpointdes

			btnShareYourPoint = (Button) layout.findViewById(R.id.send_Point);
			btnShareYourPoint.setOnClickListener(this);

			btnClosePopupPoint = (Button) layout
					.findViewById(R.id.btn_close_popup_point);
			btnClosePopupPoint.setOnClickListener(this);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onClick(View v) {

		// ROUTE button
		if (v == buttonAddRoute) {
			initiatePopupWindowRoute();

		}

		// markers2
		if (v == btnShareYourRoute) {
			
			//Debug.startMethodTracing("myapp");
			new AddRouteTask(routeData, pwindo).execute(new RouteDetails(
					etRouteName.getText().toString(), etRouteDes.getText()
							.toString(), markerPoints, listOfPoint, appData
							.getIdUser()));
			//Debug.stopMethodTracing();

			// if (SaveRoadToDatabase(markerPoints)) {
			// Toast.makeText(getBaseContext(), " Adding routes",
			// Toast.LENGTH_SHORT).show();
			// }
		}

		if (v == btnClosePopup) {
			pwindo.dismiss();
		}

		// POINT button
		if (v == buttonAddPoint) {
			initiatePopupWindowPoint();

		}

		if (v == btnShareYourPoint) {

			if (addPointFunction()) {
				Toast.makeText(getBaseContext(), "The point is added",
						Toast.LENGTH_SHORT).show();
			}
		}

		if (v == btnClosePopupPoint) {
			pwindopoint.dismiss();
		}

	}

	// adding characteristic Point
	public boolean addPointFunction() {
		boolean isAdd = false;

		try {

			LatLng coordinate = getLastCoordination();
			String descriptionPoint = etPointDes.getText().toString();
			String namePoint = etPointName.getText().toString();

			if (descriptionPoint != null && namePoint != null) {
				isAdd = true;
				listOfPoint.add(new CharacteristicPoint(coordinate, namePoint,
						descriptionPoint));

				pwindopoint.dismiss();
				Toast.makeText(getBaseContext(), "Adding point",
						Toast.LENGTH_SHORT).show();

			} else {
				Toast.makeText(getBaseContext(), "desc i name point is null",
						Toast.LENGTH_SHORT).show();
			}

		} catch (Exception e) {

			e.printStackTrace();
			// Display toast when there is a conncetion error
			Toast.makeText(getBaseContext(), "Cannot add point",
					Toast.LENGTH_SHORT).show();

		}

		return isAdd;

	}

	// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	public void createGoogleMap(Bundle bundle) {

		try {
			// Initializing
			markerPoints = new ArrayList<LatLng>();

			// Getting reference to SupportMapFragment of the activity_main
			fm = (SupportMapFragment) getSupportFragmentManager()
					.findFragmentById(R.id.map);

			// Getting Map for the SupportMapFragment
			googleMap = fm.getMap();

			// Enable MyLocation Button in the Map
			googleMap.setMyLocationEnabled(true);

			// Getting LocationManager object from System Service
			// LOCATION_SERVICE
			LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

			// Define a listener that responds to location updates
			locationListener = new MyLocationListener();

			locationManager.requestLocationUpdates(
					LocationManager.NETWORK_PROVIDER, 0, 0, this.locationListener);

			// Creating a criteria object to retrieve provider
			Criteria criteria = new Criteria();

			// Getting the name of the best provider
			String provider = locationManager.getBestProvider(criteria, true);

			ArrayList<LatLng> coordinates = null;
			// Getting Current Location From GPS
			if (isRouteDrawing) {

				getMenuItem = true;
				Location location = locationManager
						.getLastKnownLocation(provider);

				mLatitude = location.getLatitude();
				mLongitude = location.getLongitude();
				LatLng point = new LatLng(mLatitude, mLongitude);

				markerPoints.add(point);

				// firstLocation.add(point);

				/*
				 * MarkerOptions options = new MarkerOptions();
				 * options.position(markerPoints.get(0));
				 * options.icon(BitmapDescriptorFactory
				 * .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
				 * googleMap.addMarker(options);
				 */

				googleMap.moveCamera(CameraUpdateFactory.newLatLng(point));
				googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));

				// wpiszWspolrzedne();
				/*
				 * if (location != null ) { onLocationChanged(location); }
				 */

				/*
				 * if (isPressedStartButton && location != null) {
				 * onLocationChanged(listaWspolrzednych); //drawCurrentPath(); }
				 */

			} else {

				time1 = System.currentTimeMillis();
				android.util.Log.i("Time Class Dispay Route ", " Time 1 value in millisecinds "+ time1);
				coordinates = CoordinatesParser
						.getCoordinatesFromString(routeInfo.getCoordinates());

				LatLng cord = coordinates.get(0);
				int zoom = 14;
				googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
						new LatLng(cord.latitude, cord.longitude), zoom));
				// unregisterForContextMenu(getListView());
			}

			// checkCurrentPosition(locationManager, provider);
			createGoogleMapsListeners();

			if (routeInfo != null) {
				try {

					drawRoute(coordinates);
					drawPoints(routeInfo.getCharacteristicPoints());
					time2 = System.currentTimeMillis();
					android.util.Log.i("Time Class Dispay Route ", " Time 2 value in millisecinds "+time2);
					timeEnd = time2 - time1;
					android.util.Log.i("Time Class ", " roznica "+ timeEnd);

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			// googleMap.setOnMarkerClickListener(listener);
			fm.getMap().setOnInfoWindowClickListener(
					new OnInfoWindowClickListener() {

						@Override
						public void onInfoWindowClick(Marker marker) {
							try {
								String clickedMarkerId = marker.getId();
								int characteristicPointId = Integer
										.parseInt(marker.getSnippet()) - 1;

								String desc = characteristicPoints.get(
										characteristicPointId).getDescription();
								String name = characteristicPoints.get(
										characteristicPointId).getNamePoint();
								AlertDialogDescPoint(desc, name);
							} catch (Exception e) {
								e.printStackTrace();
							}

						}

					});

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private final class MyLocationListener implements LocationListener {

		@Override
		public void onLocationChanged(Location location) {
			// called when the listener is notified with a location update from
			// the GPS

			if (isPressedStartButton && !isPressedStopButton) {
				mLatitude = location.getLatitude();
				mLongitude = location.getLongitude();
				LatLng point = new LatLng(mLatitude, mLongitude);

				markerPoints.add(point);

				/*
				 * MarkerOptions options = new MarkerOptions();
				 * options.position(markerPoints.get(0));
				 * options.icon(BitmapDescriptorFactory
				 * .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
				 */

				String text = "My Current Location is:\nLatitude = "
						+ location.getLatitude() + "\nLongitude = "
						+ location.getLongitude();
				/*
				 * Toast.makeText(getApplicationContext(), text,
				 * Toast.LENGTH_SHORT) .show();
				 */

				tvGpsLocation.setText(text);

				googleMap.moveCamera(CameraUpdateFactory.newLatLng(point));
				googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));

				drawCurrentPath(point);
				// drawMarker(point);
			}
		}

		@Override
		public void onProviderDisabled(String provider) {
			Toast.makeText(getApplicationContext(), "Gps Disabled",
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onProviderEnabled(String provider) {
			Toast.makeText(getApplicationContext(), "Gps Enabled",
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {

		}
	}

	private void drawPoints(String pointsAsJSON) {
		try {
			characteristicPoints = CharacteristicPointsParser
					.getPointsFromString(pointsAsJSON);

			for (int i = 0; i < characteristicPoints.size(); i++) {

				markersList = new ArrayList<Marker>();

				Marker marker = googleMap
						.addMarker(new MarkerOptions()
								.position(
										characteristicPoints.get(i)
												.getCoordinate())
								.icon(BitmapDescriptorFactory
										.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET))
								.snippet(((Integer) (i + 1)).toString())
								.title(characteristicPoints.get(i)
										.getNamePoint()));

				/*
				 * EventInfo fEventInfo = new
				 * EventInfo(characteristicPoints.get(i).getCoordinate(),
				 * characteristicPoints.get(i).getNamePoint(),
				 * characteristicPoints.get(i).getDescription());
				 */

				// Marker fmarker = fm.placeMarker(fEventInfo);

				markersList.add(marker);

				// makrersList.add();
				// Marker marker =
				// googleMap.addMarker(new
				// MarkerOptions().position(characteristicPoints.get(i).getCoordinate()).title(characteristicPoints.get(i).getNamePoint())).showInfoWindow();
				// marker.showInfoWindow();

			}

			/*
			 * (markerPoints.size() == 1) { options.icon(BitmapDescriptorFactory
			 * .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
			 */

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void drawRoute(ArrayList<LatLng> coordinates) {
		for (int i = 0; i < coordinates.size() - 1; i++) {
			// Latlng StartPoint = coordinates.get(0)
			LatLng src = coordinates.get(i);
			LatLng dest = coordinates.get(i + 1);

			/*
			 * MarkerOptions options = new MarkerOptions();
			 * options.position(coordinates.get(i));
			 */
			if (i == 0) {
				/*
				 * options.icon(BitmapDescriptorFactory
				 * .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
				 */
				Marker marker = googleMap
						.addMarker(new MarkerOptions()
								.position(coordinates.get(i))
								.icon(BitmapDescriptorFactory
										.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
								.title("START"));

				/*
				 * Marker marker2 = myMap.addMarker(new MarkerOptions()
				 * .position(latLng) .title("START") .snippet("Snippet")
				 * .icon(BitmapDescriptorFactory
				 * .fromResource(R.drawable.marker2)));
				 */
				// marker.showInfoWindow();

			} else if (i + 1 == coordinates.size() - 1) {

				/*
				 * options.icon(BitmapDescriptorFactory
				 * .defaultMarker(BitmapDescriptorFactory.HUE_RED));
				 */

				Marker marker2 = googleMap
						.addMarker(new MarkerOptions()
								.position(coordinates.get(i + 1))
								.icon(BitmapDescriptorFactory
										.defaultMarker(BitmapDescriptorFactory.HUE_RED))
								.title("STOP"));

				// marker2.showInfoWindow();
			}

			Polyline line = googleMap.addPolyline(new PolylineOptions()
					.add(new LatLng(src.latitude, src.longitude),
							new LatLng(dest.latitude, dest.longitude)).width(5)
					.color(Color.BLUE).geodesic(true));
		}
	}

	public void drawCurrentPath(LatLng point) {
		markerPoints.add(point);
		// drawStartStopMarker();
		// Checks, whether start and end locations are captured
		if (SizeOfmarkersPointsArray() >= 2) {
			LatLng origin = markerPoints.get(0);
			LatLng dest = markerPoints.get(1);

			/*
			 * // Getting URL to the Google Directions API String url =
			 * getDirectionsUrl(origin, dest);
			 * 
			 * DownloadTask downloadTask = new DownloadTask();
			 * 
			 * // Start downloading json data from Google Directions API
			 * downloadTask.execute(url);
			 */

		}

		// displaying polyline on map
		for (int i = 0; i < SizeOfmarkersPointsArray() - 1; i++) {
			LatLng src = markerPoints.get(i);
			LatLng dest = markerPoints.get(i + 1);
			Polyline line = googleMap.addPolyline(new PolylineOptions()
					// mMap is the Map Object
					.add(new LatLng(src.latitude, src.longitude),
							new LatLng(dest.latitude, dest.longitude)).width(5)
					.color(Color.BLUE).geodesic(true));
		}

	}

	// Setting onclick event listener for the map
	public void createGoogleMapsListeners() {
		googleMap.setOnMapClickListener(new OnMapClickListener() {

			@Override
			public void onMapClick(LatLng point) {

				if (!isPressedStartButton && isPressedStopButton) {
					markerPoints.add(point);

					if (SizeOfmarkersPointsArray() >= 2) {
						LatLng origin = markerPoints.get(0);
						LatLng dest = markerPoints.get(1);
					}

					// displaying polyline on map
					for (int i = 0; i < SizeOfmarkersPointsArray() - 1; i++) {
						LatLng src = markerPoints.get(i);
						LatLng dest = markerPoints.get(i + 1);
						Polyline line = googleMap
								.addPolyline(new PolylineOptions()
										// mMap is the Map Object
										.add(new LatLng(src.latitude,
												src.longitude),
												new LatLng(dest.latitude,
														dest.longitude))
										.width(5).color(Color.BLUE)
										.geodesic(true));
					}
				}
			}
		});
	}

	// current position
	public void checkCurrentPosition(LocationManager locationManager,
			String provider) {
		locationManager.requestLocationUpdates(provider, 0, 0, this);
	}

	public LatLng getLastCoordination() {

		LatLng coordinate = markerPoints.get(SizeOfmarkersPointsArray() - 1);

		return coordinate;

	}

	// Drawing Start and Stop locations
	public void drawStartStopMarker() {

		for (int i = 0; i < SizeOfmarkersPointsArray(); i++) {

			// Creating MarkerPoint
			MarkerOptions options = new MarkerOptions();

			options.position(markerPoints.get(i));
			/**
			 * For the start location, the color of marker is GREEN and for the
			 * end location, the color of marker is RED.
			 */
			/*
			 * if (i == 0) { options.icon(BitmapDescriptorFactory
			 * .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); } else if (i
			 * == 1) { options.icon(BitmapDescriptorFactory
			 * .defaultMarker(BitmapDescriptorFactory.HUE_RED)); }
			 */

			// Add new marker to the Google Map Android API V2
			googleMap.addMarker(options);

		}
	}

	private void drawMarker(LatLng point) {

		// markerPoints.add(point);
		// ad *
		markerPoints.add(point);
		// Creating MarkerOptions
		MarkerOptions options = new MarkerOptions();

		// Setting the position of the marker
		options.position(point);

		// **
		// * For the start location, the color of marker is GREEN and
		// * for the end location, the color of marker is RED.
		// *
		if (SizeOfmarkersPointsArray() == 1) {
			options.icon(BitmapDescriptorFactory
					.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
		} else if (SizeOfmarkersPointsArray() == 2) {
			options.icon(BitmapDescriptorFactory
					.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
		}

		// Add new marker to the Google Map Android API V2
		googleMap.addMarker(options);
	}

	@Override
	public void onLocationChanged(Location location) {
		// Draw the marker, if destination location is not set
		// if (markerPoints.size() < 2) {

		mLatitude = location.getLatitude();
		mLongitude = location.getLongitude();
		LatLng point = new LatLng(mLatitude, mLongitude);
		markerPoints.add(point);

		googleMap.moveCamera(CameraUpdateFactory.newLatLng(point));
		googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));

		// drawMarker(point);

		// drawCurrentPath(point);

		// if (markerPoints.size() >= 2) {
		// LatLng origin = markerPoints.get(0);
		// LatLng dest = markerPoints.get(1);

		// Getting URL to the Google Directions API
		// String url = getDirectionsUrl(origin, dest);

		// DownloadTask downloadTask = new DownloadTask();

		// Start downloading json data from Google Directions API
		// downloadTask.execute(url);
		// }
	}

	public void onLocationChanged(List<LatLng> location) {
		// Draw the marker, if destination location is not set
		// if (markerPoints.size() < 2) {

		for (LatLng latLng : location) {

			// LatLng lat = location.
			// mLatitude = loc1ation.lat);
			// mLongitude = location.getLongitude();
			// LatLng point = new LatLng(mLatitude, mLongitude);
			// markerPoints.add(lat);

			markerPoints.add(latLng);

			googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
			googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));

			drawMarker(latLng);

			drawCurrentPath(latLng);

		}

	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub

	}

	// Invoking background thread to store the touched location in Remove MySQL
	// server
	/*
	 * public void sendToServer() { SaveRoadToDatabase(markerPoints); }
	 */

	/*
	 * public void sendRouteToServer() { SavePointToDatabase(listOfPoint); }
	 */

//	private class RouteDetails {
//		String name;
//		String description;
//		List<LatLng> latLng;
//		List<CharacteristicPoint> characteristicPoints;
//		int id_user;
//
//		public RouteDetails(String name, String description,
//				List<LatLng> latLng,
//				List<CharacteristicPoint> characteristicPoints, int id_user) {
//			super();
//			this.name = name;
//			this.description = description;
//			this.latLng = latLng;
//			this.characteristicPoints = characteristicPoints;
//			this.id_user = id_user;
//		}
//
//		public String getName() {
//			return name;
//		}
//
//		public String getDescription() {
//			return description;
//		}
//
//		public List<LatLng> getLatLng() {
//			return latLng;
//		}
//
//		public List<CharacteristicPoint> getCharacteristicPoints() {
//			return characteristicPoints;
//		}
//
//		public int getId_user() {
//			return id_user;
//		}
//
//	}

	private class AddRouteTask extends AsyncTask<RouteDetails, Void, Boolean> {

		private RouteData routeData;
		private PopupWindow window;
	//	private TimingLogger timings;
		private long time;

		public AddRouteTask(RouteData routeData, PopupWindow window) {
			super();
			this.routeData = routeData;
			this.window = window;
		}
		
		protected void onPreExecute() {
			super.onPreExecute();
/*
			timings = new TimingLogger("TopicLogTag",
					"AddRouteTask");*/
			time= System.currentTimeMillis();
			android.util.Log.i("Time Class ", " Time 1 value in millisecinds "+time);
			
		}

		@Override
		protected Boolean doInBackground(RouteDetails... params) {
			
			try {
				
//				Debug.startMethodTracing("myapp2");
				RouteDetails routeDetails = params[0];
				String strUrl = "http://" + UrlClass.getUrl() + "/v1/addRoute";

				URL url = null;

				url = new URL(strUrl);

				HttpURLConnection connection = (HttpURLConnection) url
						.openConnection();
				connection.setRequestMethod("POST");
				connection.setDoOutput(true);
				OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
						connection.getOutputStream());

				outputStreamWriter.write("coordinates="
						+ CoordinatesParser
								.getStringFromCoordinates(routeDetails
										.getLatLng())
						+ "&name_route="
						+ routeDetails.getName()
						+ "&description="
						+ routeDetails.getDescription()
						+ "&points="
						+ CharacteristicPointsParser.getJSON(routeDetails
								.getCharacteristicPoints()) + "&id_user="
						+ routeDetails.getId_user());

				outputStreamWriter.flush();
				outputStreamWriter.close();

				InputStream iStream = connection.getInputStream();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(iStream));

				StringBuffer sb = new StringBuffer();
				String line = "";

				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}

				reader.close();
				iStream.close();

				String jsonResponseString = sb.toString();
				JSONObject jsonResponse = new JSONObject(jsonResponseString);

				// assign json responses to local strings
				// mysql
				// table
				boolean isAdded = !Boolean.parseBoolean(jsonResponse
						.getString("error"));

				// if (!isValidBool) {
				// String idRoute = jsonResponse.getString("name_route");
				// this.routeData.setIdRoute(idRoute);
				// }

				// Adding point to road
				// SavePointToDatabase(routeDetails.getCharacteristicPoints(),
				// routeData.getIdRoute());
//				Debug.stopMethodTracing();
				
				return isAdded;

			} catch (Exception e) {
				e.printStackTrace();
				// Display toast when there is a conncetion error
				Toast.makeText(getBaseContext(), "Connection Error Exception",
						Toast.LENGTH_SHORT).show();
			}
			return false;

		}

		@Override
		protected void onPostExecute(Boolean isRouteAdded) {
			super.onPostExecute(isRouteAdded);
			if (isRouteAdded) {
				//timings.dumpToLog();
				long time2= System.currentTimeMillis();
				android.util.Log.i("Time Class ", " Time 2 value in millisecinds "+time2);
				long timeEnd = time2 - time;
				android.util.Log.i("Time Class ", " roznica "+ timeEnd);
				this.window.dismiss();
				Toast.makeText(getBaseContext(), "Routes added! Hells Bells!",
						Toast.LENGTH_SHORT).show();
			}

		}

	}

	// nie uzywane
	// Background thread to save the location in remove MySQL server
	/*
	 * public boolean SaveRoadToDatabase(ArrayList<LatLng> latLng) {
	 * 
	 * boolean isRoute = false; String route; try {
	 * 
	 * String name_route = etRouteName.getText().toString(); String desc =
	 * etRouteDes.getText().toString();
	 * 
	 * route = CoordinatesParser.getStringFromCoordinates(latLng);
	 * 
	 * // TODO String strUrl = "http://" + UrlClass.url + "/v1/routes"; URL url
	 * = null;
	 * 
	 * try { url = new URL(strUrl);
	 * 
	 * HttpURLConnection connection = (HttpURLConnection) url .openConnection();
	 * connection.setRequestMethod("POST"); connection.setDoOutput(true);
	 * OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
	 * connection.getOutputStream());
	 * 
	 * // TODO uzyc debuggera zeby zeby zobaczyc czy wchodzi wyjatek // TODO
	 * zamiast lat lon wpisa email i password + te wartosci // pobrane wczesniej
	 * (patrz TODO) outputStreamWriter.write("coordinates=" + route +
	 * "&name_route=" + name_route + "&desc=" + desc); // write latLngString to
	 * console System.out.println(route); outputStreamWriter.flush();
	 * outputStreamWriter.close();
	 * 
	 * InputStream iStream = connection.getInputStream(); BufferedReader reader
	 * = new BufferedReader( new InputStreamReader(iStream));
	 * 
	 * StringBuffer sb = new StringBuffer();
	 * 
	 * String line = "";
	 * 
	 * while ((line = reader.readLine()) != null) { sb.append(line); }
	 * 
	 * String jsonResponseString = sb.toString(); JSONObject jsonResponse = new
	 * JSONObject(jsonResponseString);
	 * 
	 * // assign json responses to local strings String isValidString =
	 * jsonResponse.getString("error");// mysql // table boolean isValidBool =
	 * Boolean.parseBoolean(isValidString);
	 * 
	 * if (!isValidBool) { String idRoute =
	 * jsonResponse.getString("name_route"); this.routeData.setIdRoute(idRoute);
	 * isRoute = true; } else { String message =
	 * jsonResponse.getString("message"); this.tvStatus.setText(message);
	 * isRoute = false; }// field
	 * 
	 * // Adding point to road String idRoute = routeData.getIdRoute();
	 * SavePointToDatabase(listOfPoint, idRoute);
	 * 
	 * reader.close(); iStream.close();
	 * 
	 * } catch (MalformedURLException e) { e.printStackTrace();
	 * Toast.makeText(getBaseContext(), "Connection Error",
	 * Toast.LENGTH_SHORT).show(); } catch (IOException e) {
	 * e.printStackTrace(); Toast.makeText(getBaseContext(), "Connection Error",
	 * Toast.LENGTH_SHORT).show(); }
	 * 
	 * } catch (Exception e) { e.printStackTrace(); // Display toast when there
	 * is a conncetion error Toast.makeText(getBaseContext(),
	 * "Connection Error Exception", Toast.LENGTH_SHORT).show(); } return
	 * isRoute;
	 * 
	 * }
	 */
	// Background thread to save the location in remove MySQL server
	public boolean SavePointToDatabase(List<CharacteristicPoint> listOfPoint,
			String id_route) {

		// TODO zebrac warotsci z pol(email, haslo) (proste zrobisz w 5 minut)
		/*
		 * String lat = Double.toString(params[0].latitude); String lng =
		 * Double.toString(params[0].longitude);
		 */

		boolean isSendPointToDatabase = false;
		// get coordinate from charcteristicPoint
		for (int i = 0; i < listOfPoint.size(); i++) {
			CharacteristicPoint point = listOfPoint.get(i);
			LatLng coordinate = point.getCoordinate();
			String lat = Double.toString(coordinate.latitude);
			String lng = Double.toString(coordinate.longitude);
			String name_point = point.getNamePoint();
			String description = point.getDescription();

			// TODO zamiast markers wpisac login (ok 20 minut)
			String strUrl = "http://192.168.17.1/v1/characteristicpoint";
			URL url = null;
			try {
				url = new URL(strUrl);

				HttpURLConnection connection = (HttpURLConnection) url
						.openConnection();
				connection.setRequestMethod("POST");
				connection.setDoOutput(true);
				OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
						connection.getOutputStream());

				// TODO uzyc debuggera zeby zeby zobaczyc czy wchodzi wyjatek
				// TODO zamiast lat lon wpisa email i password + te wartosci
				// pobrane wczesniej (patrz TODO) (ok 50 minut)
				outputStreamWriter.write("lat=" + lat + "&lng=" + lng
						+ "&name_point=" + name_point + "&description="
						+ description + "&id_route=" + id_route);
				outputStreamWriter.flush();
				outputStreamWriter.close();

				InputStream iStream = connection.getInputStream();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(iStream));

				StringBuffer sb = new StringBuffer();

				String line = "";

				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}

				//
				String jsonResponseString = sb.toString();
				JSONObject jsonResponse = new JSONObject(jsonResponseString);

				// assign json responses to local strings
				String hasErrorsString = jsonResponse.getString("error");// mysql
																			// table
																			// field
				boolean hasErrorsBool = Boolean.parseBoolean(hasErrorsString);

				if (!hasErrorsBool) {
					this.appData.setUserMail(lat);
					isSendPointToDatabase = true;
				} else {
					String message = jsonResponse.getString("message");
					this.tvStatus.setText(message);
					isSendPointToDatabase = false;
				}
				//

				reader.close();
				iStream.close();

			} catch (MalformedURLException e) {
				e.printStackTrace();
				Toast.makeText(getBaseContext(), "Connection Error",
						Toast.LENGTH_SHORT).show();

			} catch (IOException e) {
				e.printStackTrace();
				Toast.makeText(getBaseContext(), "Connection Error",
						Toast.LENGTH_SHORT).show();

			} catch (Exception e) {
				e.printStackTrace();
				// Display toast when there is a conncetion error
				Toast.makeText(getBaseContext(), "Connection Error Exception",
						Toast.LENGTH_SHORT).show();
			}

		}
		return isSendPointToDatabase;

	}

}
